import { IRoleManageTitle } from '../type';
import cls from 'classnames';
import { ChangeEvent, useCallback, useContext, useMemo, useState } from 'react';
import { RouleManageContext } from '../hooks';
import { TypographyTitle } from '@/components/Typography';
import { AutoComplete, Button, Empty, Input, Space } from 'antd';
import {
  SearchOutlined,
  ReloadOutlined,
  PlusOutlined,
} from '@ant-design/icons';
import { loopArray } from '@/utils';
import { RoleAddEditModal } from './RoleAddEditModal';
export const RoleManageTitle: React.FC<IRoleManageTitle> = ({
  reloadRoleTable,
}) => {
  const {
    prefixCls,
    rouleDispatch,
    curRes,
    tableLoading,
    tableData,
    searchTableValue,
    checkedRowKeys,
  } = useContext(RouleManageContext); //获取 上下文

  const [roleAddEdit, setRoleAddEdit] = useState<boolean>(false);
  const openRoleModal = useCallback(
    (isShow: boolean) => {
      setRoleAddEdit(isShow);
    },
    [roleAddEdit],
  );

  // 搜索下拉菜单
  const autoOption = useMemo(() => {
    let option: Record<string, any>[] = [];
    const tileTreeData = (data: Record<string, any>[]) => {
      data?.forEach((item) => {
        if (item?.children && item?.children?.length > 0) {
          tileTreeData(item?.children);
        }
        if (item?.name?.includes(searchTableValue)) {
          // const name = item?.name;
          // const nameLength = name?.length;
          // const select = name?.search(searchTableValue);
          // const searchLength = searchTableValue?.length;
          // const afterStr = name?.slice(0, select);
          // const selectStr = searchTableValue;
          // const beforeStr = name?.slice(select + searchLength, nameLength);
          option.push({
            value: item?.name,
            key: item?.id,
            // label: (
            //   <div>
            //     <span>{afterStr}</span>
            //     <span style={{ color: '#f50' }}>{selectStr}</span>
            //     <span>{beforeStr}</span>
            //   </div>
            // ),
          });
        }
      });
    };
    tileTreeData(tableData);
    return option;
  }, [tableData, searchTableValue]);

  // 点击搜索
  const onAutoSelect = (value: string, option: any) => {
    const promise = new Promise((resolve, reject) => {
      const optionId = option?.key;
      const targetNode = loopArray(tableData)?.find((i) => i?.id == optionId);
      rouleDispatch({
        type: 'role-expandedRowKeys',
        payload: [targetNode?.pID],
      });

      rouleDispatch({
        type: 'role-checkedRowKeys',
        payload: [optionId],
      });

      rouleDispatch({
        type: 'role-searchTableValue',
        payload: value,
      });

      setTimeout(() => {
        scrollToAnchor(optionId);
      }, 1000);

      resolve(optionId);
    });
    promise.then((res: any) => {
      if (res) {
        // reloadRoleTable();
      }
    });
  };

  // 滚动定位
  const scrollToAnchor = (id: string) => {
    let anchorElement = document.getElementById(id);
    if (id) {
      anchorElement?.scrollIntoView({ block: 'start', behavior: 'smooth' });
    }
  };

  // 搜索框改变
  const onInputChange = (e: ChangeEvent<HTMLInputElement>) => {
    rouleDispatch({
      type: 'role-searchTableValue',
      payload: e.target.value,
    });
  };

  return (
    <>
      <div className={cls(prefixCls + 'table-header')}>
        <TypographyTitle
          level={4}
          style={{
            margin: 0,
          }}
        >
          角色管理
        </TypographyTitle>
        <div className={cls(prefixCls + 'table-search')}>
          <Space>
            <AutoComplete
              style={{
                width: 400,
              }}
              options={autoOption}
              onSelect={onAutoSelect}
              notFoundContent={<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
            >
              <Input
                placeholder={'请按名称搜索'}
                suffix={<SearchOutlined />}
                onChange={onInputChange}
                addonAfter={
                  <ReloadOutlined
                    onClick={() => {
                      // rouleDispatch({
                      //   type: 'range-searchTableValue',
                      //   payload: '',
                      // });
                      // rouleDispatch({
                      //   type: 'range-expandedRowKeys',
                      //   payload: [],
                      // });
                      reloadRoleTable();
                    }}
                  />
                }
                allowClear
              />
            </AutoComplete>
            {curRes['/roleController/add'] && (
              <Button
                type={'primary'}
                icon={<PlusOutlined />}
                onClick={() => {
                  openRoleModal(true);
                }}
                disabled={tableLoading}
              >
                添加
              </Button>
            )}
          </Space>
        </div>
      </div>

      {/* 新增弹框 */}
      {roleAddEdit && (
        <RoleAddEditModal
          visible={roleAddEdit}
          onClose={() => {
            openRoleModal(false);
          }}
          editAddRows={{}}
          tableReload={reloadRoleTable}
        />
      )}
    </>
  );
};
